﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.Utility
{
    /// <summary>
    /// 用于DataTable WebApi返回DataTable信息；
    /// 主要处理DataTable为0行时，无法返回DataTable列信息的情况
    /// </summary>
    public class DataTableInfo
    {
        private DataTable webApiData = new DataTable();

        /// <summary>
        /// 列信息
        /// </summary>
        [JsonProperty("column_info")]
        public List<DataColumn> ColumnInfo { get; set; } = new List<DataColumn>();

        /// <summary>
        /// WebApi返回的表信息
        /// </summary>
        [JsonProperty("web_api_data")]
        public DataTable WebApiData { get => webApiData; set => webApiData = value; }
        /// <summary>
        /// 表信息
        /// </summary>
        //[JsonProperty("column_info")]
        [JsonIgnore]
        public DataTable Data
        {
            get
            {
                DataTable res = webApiData;
                if(webApiData.Columns.Count == 0 && ColumnInfo != null)
                {
                    res = new DataTable();
                    foreach(var columnItem in ColumnInfo)
                    {
                        res.Columns.Add(columnItem);
                    }
                }
                return res;
            }
        }

        /// <summary>
        /// 设置DataTableInfo
        /// </summary>
        /// <param name="dataTable"></param>
        /// <returns></returns>
        public static DataTableInfo SetDataTableInfo(DataTable? dataTable)
        {
            DataTableInfo res = new DataTableInfo();
            if (dataTable != null)
            {
                foreach (DataColumn column in dataTable.Columns)
                {
                    res.ColumnInfo.Add(column);
                }
                res.WebApiData = dataTable;
            }
            return res;
        }
    }
}
